package com.ricohgag.controller.home;

import com.ricohgag.entity.Goods;
import com.ricohgag.entity.UserAddress;
import com.ricohgag.entity.UserCartLog;
import com.ricohgag.entity.VipUser;
import com.ricohgag.entity.custom.UserCartLogVo;
import com.ricohgag.service.*;
import com.ricohgag.util.Msg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @author ricohgag
 * @date 2018/9/5 16:12
 */
@Controller
@RequestMapping("/home/cart")
public class HomeCartController {
    @Autowired
    private UserCartLogService userCartLogService;
    @Autowired
    private UserAddressService userAddressService;
    @Autowired
    private ShopOrderService shopOrderService;
    @Autowired
    private ShopOrderGoodsService shopOrderGoodsService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private  VipUserService vipUserService;


    @RequestMapping("/index")
    public ModelAndView index(HttpServletRequest request) throws Exception{
        ModelAndView mav = new ModelAndView("/home/cart/index");
        mav.addObject("navActive", 2);

        VipUser vipUser = (VipUser) request.getSession().getAttribute("vipUserSession");

        if(vipUser == null){
            mav.setViewName("redirect:/home/index/index");
        } else {
            List<UserCartLogVo> userCartLogVos = userCartLogService.selectCartVoByUserId(vipUser.getId());
            mav.addObject("userCartLogVos", userCartLogVos);
        }

        return mav;
    }

    @RequestMapping("/submitCart")
    @ResponseBody
    public Msg submitCart(HttpServletRequest request, Integer goodsId, Integer goodsNum) throws Exception{
        Msg msg = new Msg();
        VipUser vipUser = (VipUser)request.getSession().getAttribute("vipUserSession");
        Goods goods = goodsService.selectGoodsOne(goodsId);

        //没有登录，跳转登录页面
        if(vipUser == null){
            msg.setStatus(2);
            return msg;
        }
        //库存小于购买数量
        if(goods.getGoodsNumber()<goodsNum){
            msg.setStatus(-1);
            return msg;
        }

        List<UserCartLogVo> userCartLogVos = userCartLogService.selectCartVoByUserId(vipUser.getId());
        UserCartLog userCartLog;
        //查看购物车是否有同个商品，有则加数量
        for(UserCartLogVo userCartLogVo:userCartLogVos){
            userCartLog = userCartLogVo.getUserCartLog();
            if(goodsId.equals(userCartLog.getGoodsId())){
                userCartLog.setGoNum(userCartLog.getGoNum()+goodsNum);
                int count = userCartLogService.update(userCartLog);
                if(count>0){
                    msg.setStatus(1);
                } else {
                    msg.setStatus(0);
                }

                return msg;
            }
        }

        //新增商品到购物车
        userCartLog = new UserCartLog();
        userCartLog.setUserId(vipUser.getId());
        userCartLog.setGoodsId(goodsId);
        userCartLog.setAddTime(LocalDateTime.now());
        userCartLog.setGoNum(goodsNum);

        int count = userCartLogService.insertCartLog(userCartLog);
        if(count >0){
            msg.setStatus(1);
        } else {
            msg.setStatus(0);
        }

        return  msg;
    }

    @RequestMapping("/delete")
    @ResponseBody
    public Msg delete(Integer id) throws Exception{
        Msg msg = new Msg();
        int count = userCartLogService.delete(id);
        if(count > 0){
            msg.setStatus(1);
            msg.setMsg("删除成功");
        } else {
            msg.setStatus(0);
            msg.setMsg("删除失败");
        }
        return msg;
    }


    /*********************订单********************/
    @RequestMapping("/writeorder")
    public ModelAndView writeorder(HttpServletRequest request) throws Exception{
        ModelAndView mav = new ModelAndView("/home/cart/writeorder");
        VipUser vipUser = (VipUser)request.getSession().getAttribute("vipUserSession");
        List<UserAddress> addressList = userAddressService.selectAddressByUserId(vipUser.getId());
        mav.addObject("addressList", addressList);
        mav.addObject("navActive", 2);

        List<UserCartLogVo> userCartLogVos = userCartLogService.selectCartVoByUserId(vipUser.getId());
        mav.addObject("userCartLogVos", userCartLogVos);

        return mav;
    }

    /**
     * 跳转到
     * @param address
     * @return
     */
    @RequestMapping("/addAddress")
    public String addAddress(UserAddress address){

        return "/home/cart/addAddress";
    }

    @RequestMapping("/submitAddress")
    public String submitAddress(HttpServletRequest request, UserAddress address) throws Exception{
        VipUser vipUser = (VipUser)request.getSession().getAttribute("vipUserSession");
        address.setUserId(vipUser.getId());

        userAddressService.insert(address);

        return "redirect:/home/cart/writeorder";
    }


    /**
     * 实现支付功能
     * @param request
     * @param addId
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/pay")
    public Msg pay(HttpServletRequest request, Integer addId, String message) throws Exception{
        Msg msg = new Msg();
        //得到session的用户id去查询实时用户
        VipUser vipUserSession = (VipUser)request.getSession().getAttribute("vipUserSession");
        VipUser vipUser = vipUserService.selectVipUserOne(vipUserSession.getId());
        List<UserCartLogVo> userCartLogVos =  userCartLogService.selectCartVoByUserId(vipUser.getId());
        System.err.println("userCartLogVos: "+userCartLogVos);
        BigDecimal moneySum = new BigDecimal(0);
        for(UserCartLogVo userCartLogVo:userCartLogVos){
           moneySum = moneySum.add(userCartLogVo.getTotalPrice());
        }
        if(moneySum.compareTo(vipUser.getRechargeMoney())==1){
            msg.setMsg("余额不足，请充值");
            msg.setStatus(-1);
            return msg;
        }

        //得到当前时间，生成订单号
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMddHHmmSSS");
        String orderSn = dtf.format(LocalDateTime.now());
        //得到根据地址id得到地址
        UserAddress address = userAddressService.selectOneById(addId);

        //生成订单和订单商品关联，
        int count = shopOrderService.insertShopOrder(orderSn, address, moneySum, message);
        //插入订单记录
        shopOrderGoodsService.insertOrderGoods(orderSn, vipUser, userCartLogVos, moneySum);
        //减少商品数量
        for(UserCartLogVo userCartLogVo:userCartLogVos){
            Goods goods = userCartLogVo.getGoods();
            goods.setGoodsNumber(goods.getGoodsNumber()-userCartLogVo.getUserCartLog().getGoNum());
            goodsService.updateGoods(goods);
        }
        //删除购物车记录
        userCartLogService.deleteByUserId(vipUser.getId());

        if(count == 0){
            msg.setStatus(2);
            msg.setMsg("插入失败");
            return msg;
        }

        msg.setMsg("购买成功！！！");
        msg.setStatus(1);
        return msg;
    }

    /**
     * 进入支付页面
     * @return
     */
    @RequestMapping("/toPay")
    public String toPay(){

        return "/home/cart/pay";
    }


    /**
     * 在购物车中更改商品数量
     */
    @RequestMapping("/changeNum")
    @ResponseBody
    public Msg changeCartNum(Integer id, Integer num, HttpServletRequest request) throws Exception{
        Msg msg = new Msg();

        VipUser vipUser = (VipUser)request.getSession().getAttribute("vipUserSession");
        boolean flag = false;

        int nowNum = goodsService.selectGoodsOne(id).getGoodsNumber();
        if(num <= nowNum){
            flag = userCartLogService.updateByGoodsId(id, vipUser.getId(), num);
        }
        System.err.println("id: "+id+"num: "+num+"nowNum: "+nowNum);
        if(flag){
            msg.setStatus(1);
            msg.setData(num);
        } else {
            msg.setStatus(2);
            msg.setData(nowNum);
            msg.setMsg("商品库存不够请重新更改");
        }
        return msg;
    }




}
